package com.college.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.college.dao.UserCredentialsDao;
import com.college.domain.User;

public class UserCredentialsDaoImpl implements UserCredentialsDao {

	private static String ADD_USER_QUERY="FROM User user WHERE user.userName =";
	private static String DELETE_USER_QUERY="delete User user WHERE user.userName =";
	
	private static HibernateTemplate hibernateTemplate;
	   
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}
	
	
	@Override
	public boolean addUserCredentials(User user) {
		
		@SuppressWarnings("unchecked")
		List<User> userList=hibernateTemplate.find( ADD_USER_QUERY+ user.getUserName());

		if(userList.size()==0){
			hibernateTemplate.saveOrUpdate(user);
			return true;
		}else{
			return false;
		}
	}

	@Override
	public boolean deleteUserCredentials(String userName) {
		
		SessionFactory sessionFactory= hibernateTemplate.getSessionFactory();
		Session session = sessionFactory.openSession();
		
		 Query qry = session.createQuery(DELETE_USER_QUERY+userName);
		
		int res = qry.executeUpdate();
		session.close();
		sessionFactory.close();
	
		if(res>0){
			return true;
		}else{
			return false;
		}
	}

}
